﻿using Windows.Storage;
using Windows.System;
using Microsoft.Xaml.Interactivity;

namespace DimensionsHelper.Client.WinUi.Behaviors;

public class HyperlinkButtonLocalUriBehavior : Behavior<HyperlinkButton>
{
    public static readonly DependencyProperty ButtonProperty = DependencyProperty.Register(
        "Button",
        typeof(HyperlinkButton),
        typeof(HyperlinkButtonLocalUriBehavior),
        new PropertyMetadata(null));


    public HyperlinkButton? Button
    {
        get => GetValue(ButtonProperty) as HyperlinkButton;
        set => SetValue(ButtonProperty, value);
    }


    protected override void OnAttached()
    {
        base.OnAttached();

        HyperlinkButton? button = Button;
        if (button != null)
        {
            button.Click += OnLaunchLocalPath;
        }
    }


    protected override void OnDetaching()
    {
        base.OnDetaching();

        HyperlinkButton? button = Button;
        if (button != null)
        {
            button.Click -= OnLaunchLocalPath;
        }
    }


    private static async void OnLaunchLocalPath(object sender, RoutedEventArgs arg)
    {
        HyperlinkButton button = (HyperlinkButton)sender;

        if (button.NavigateUri is null)
        {
            return;
        }

        string path = StringHelper.UnescapeLocalPathUriString(button.NavigateUri.LocalPath);

        try
        {
            if (File.Exists(path))
            {
                StorageFile file = await StorageFile.GetFileFromPathAsync(path);
                await Launcher.LaunchFileAsync(file);
            }
            else if (Directory.Exists(path))
            {
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);
                await Launcher.LaunchFolderAsync(folder);
            }
        }
        catch (Exception e)
        {
            await App.GetService<IMessageService>().ShowAsync(e.Message, "AppErrorLabel".GetLocalized());
        }
    }
}